package com.py.credit.controller;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.Page;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.MsgContentEntity;
import com.py.credit.entity.MsgDetailEntity;
import com.py.credit.entity.Removal;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.PluginResultObj;
import com.py.credit.service.*;
import com.py.credit.utils.IpUtil;
import com.py.credit.utils.UuidUtil;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 联合奖惩插件接口controller
 */
@Controller
@RequestMapping(value="/plugin/api")
public class PluginApiController{

	@Autowired
	private PluginApiService pluginApiService;

	@Autowired
	private OfficeService officeService;

	@Autowired
	private LhjcRemoteBaseService lhjcRemoteBaseService;

	@Autowired
	private FeedbackService feedbackService;

	@Autowired
	private SyslogService syslogService;

	@Autowired
	private RemovalService removalService;

	/**
	 * 插件登录方法
	 * @param username
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/login")
	public Object pluginLogin(@RequestParam(defaultValue = "", required = true, value = "username") String username,
							  @RequestParam(defaultValue = "", required = true, value = "password") String password){
		// 非空
		if(!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)){
			// 匹配用户名密码，返回token(token采用用户idBase64加密生成)
			Long userId = pluginApiService.checkLogin(username, password).getData();
			if(null!=userId && userId>0){
				try {
					String token = Base64.getEncoder().encodeToString((userId + "").getBytes("utf-8"));
					LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();
					Map<String,Object> content=new HashMap<String, Object>();
					content.put("token",token);
					content.put("userInfo",userInfo);
					content.put("userUrl",pluginApiService.selectAllUrl(userId));
					content.put("grade",pluginApiService.selectUserGrade(userId));

					return resultJson(PluginResultObj.CODE_SUCCESS,"登录成功",content);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"错误的用户名密码",null);
	}

	/**
	 * 获取企业信息列表
	 * @param token
	 * @param qyList
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/fetchList")
	public Object fetchList(@RequestParam(defaultValue = "", required = true, value = "token") String token,
							@RequestParam(defaultValue = "", required = true, value = "qyList") String qyList,
							HttpServletRequest request){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				String deptId= officeService.selectTopDeptId((String) userInfo.get("deptId"));

				//json解析字符串
				JSONArray qymcList=JSON.parseArray(qyList);
				List<List<LinkedHashMap>> data=new ArrayList<List<LinkedHashMap>>();
				for(int i=0;i<qymcList.size();i++){
					if(qymcList.getString(i)==null || qymcList.getString(i).equals("")){
						data.add(new ArrayList<LinkedHashMap>());
					}else{
						data.add(pluginApiService.getDeptAjbhList(deptId,qymcList.getString(i)));
						pluginApiService.insertApiLog(userId,qymcList.getString(i),"", IpUtil.getIpAddr(request));
					}
				}

				return resultJson(PluginResultObj.CODE_SUCCESS,"奖惩企业列表",data);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	/**
	 * 获取企业信息详情
	 * @param token
	 * @param ztmc
	 * @param jclb
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/fetchDetail")
	public Object fetchDetail(@RequestParam(defaultValue = "", required = true, value = "token") String token,
							  @RequestParam(defaultValue = "", required = true, value = "ztmc") String ztmc,
							  @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				String deptId= officeService.selectTopDeptId((String) userInfo.get("deptId"));

				Map<String,Object> data=new HashMap<String,Object>();
				LinkedHashMap companyInfo=pluginApiService.getCompanyInfo(ztmc).getData();
				String label = pluginApiService.getLabel(deptId,ztmc, jclb);
				companyInfo.put("label",label);
				List<LinkedHashMap> csList = pluginApiService.getCsList(deptId,label,jclb);
				for (LinkedHashMap cs:csList
						) {
					cs.put("ajbh",pluginApiService.selectAjbhByCsIdAndZtmc(deptId,(String) cs.get("id"),ztmc,jclb));
				}
				data.put("companyInfo",companyInfo);
				data.put("csList",csList);
				return resultJson(PluginResultObj.CODE_SUCCESS,"奖惩企业详情",data);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	/**
	 * 添加反馈信息
	 * @param token
	 * @param mess
	 * @param csList
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/feedback")
	public Object feedback(@RequestParam(defaultValue = "", required = true, value = "token") String token,
						   @RequestParam(defaultValue = "", required = true, value = "mess") String mess,
						   @RequestParam(defaultValue = "", required = true, value = "csList") String csList,
						   HttpServletRequest request){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				String deptId= officeService.selectTopDeptId((String) userInfo.get("deptId"));

				//json解析字符串
				JSONArray csArray=JSON.parseArray(csList);
				Timestamp feedbackTime=new Timestamp(System.currentTimeMillis());
				if(csArray.size()==0){
					return resultJson(PluginResultObj.CODE_FAIL,"反馈措施未勾选",null);
				}else{
					String batchId = UuidUtil.getInstance().getUUid();
					for(int i=0;i<csArray.size();i++){
						JSONObject cs=csArray.getJSONObject(i);
						String[] ajbhArray = cs.getString("ajbh").split(",");
						for(int j=0;j<ajbhArray.length;j++){
							int feedbackId=pluginApiService.insertFeedbackInfo(userId,Long.parseLong(deptId),ajbhArray[j],feedbackTime,mess,batchId, (String) userInfo.get("realName"));
							pluginApiService.insertFeedbackCs(feedbackId,cs.getString("id"),batchId);
							pluginApiService.modifyMess(feedbackTime,ajbhArray[j]);

							Removal rm = removalService.selectInfo(ajbhArray[j]);

							//消息中心发送信息
							Integer mbId = null;

							if(rm.getJclb().equals("C")){
								mbId = removalService.selectMbId("B");
							}else{
								mbId = removalService.selectMbId("J");
							}

							HashSet<Long> managerIdList = new HashSet<Long>();

							if(null!=mbId){
								List<MsgContentEntity> msgContentEntityList = new ArrayList<MsgContentEntity>();

								List<Long> topAndDownwardIdList = officeService.selectTopAndDownwardId(Long.parseLong(rm.getCfbm()+""));
								List<Long> managerList = lhjcRemoteBaseService.getDeptManager(org.apache.commons.lang.StringUtils.join(topAndDownwardIdList, ","), HttpServletHelper.getUserToken(request));

								if(managerList!=null && managerList.size()!=0){
									managerIdList.addAll(managerList);
								}

								if(managerIdList.size()!=0){
									MsgContentEntity msgContentEntity = new MsgContentEntity();
									if (rm.getJclb().equals("C")) {
										msgContentEntity.setMsgTitle("联合惩戒反馈");
										msgContentEntity.setMsgTypeS("B");
									} else {
										msgContentEntity.setMsgTitle("联合激励反馈");
										msgContentEntity.setMsgTypeS("J");
									}

									msgContentEntity.setMsgContent(feedbackService.getContent(syslogService.selectMbInfo(mbId),rm.getJclb(),ajbhArray[j],rm.getZtmc()));
									msgContentEntity.setMsgType(4);
									msgContentEntity.setSendId(userId);
									msgContentEntity.setSendName((String) userInfo.get("realName"));

									List<MsgDetailEntity> msgDetailEntityList = new ArrayList<MsgDetailEntity>();

									for (Long managerId : managerIdList) {
										MsgDetailEntity msgDetailEntity = new MsgDetailEntity();
										msgDetailEntity.setReviever(managerId);
										msgDetailEntity.setRevieveType(1);
										msgDetailEntityList.add(msgDetailEntity);
									}

									msgContentEntity.setDetails(msgDetailEntityList);
									msgContentEntityList.add(msgContentEntity);
								}

								lhjcRemoteBaseService.sendMsg(msgContentEntityList, HttpServletHelper.getUserToken(request));
							}

							syslogService.addProcess(ajbhArray[j], "B" + rm.getJclb(), "Y", (String) userInfo.get("username"),(String) userInfo.get("realName"), userId,Long.parseLong((String) userInfo.get("deptId")));
						}
					}

					return resultJson(PluginResultObj.CODE_SUCCESS,"反馈成功",null);
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	/**
	 * 查询url列表
	 * @param token
	 * @param page
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/urlList")
	public Object urlList(@RequestParam(defaultValue = "", required = true, value = "token") String token,Page page){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				Map<String,Object> content=new HashMap<>();
				content.put("data",pluginApiService.selectUrlForPage(userId,page));
				content.put("totalCount",page.getTotalCount());

				return resultJson(PluginResultObj.CODE_SUCCESS,"url列表",content);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	/**
	 * 新增url
	 * @param token
	 * @param urlName
	 * @param url
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addUrl")
	public Object addUrl(@RequestParam(defaultValue = "", required = true, value = "token") String token,
						 @RequestParam(defaultValue = "", required = true, value = "urlName") String urlName,
						 @RequestParam(defaultValue = "", required = true, value = "url") String url){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				pluginApiService.insertUrl(urlName, url,userId);
				return resultJson(PluginResultObj.CODE_SUCCESS,"操作成功",null);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	/**
	 * 修改url
	 * @param token
	 * @param urlName
	 * @param url
	 * @param status
	 * @param delFlag
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/modifyUrl")
	public Object modifyUrl(@RequestParam(defaultValue = "", required = true, value = "token") String token,
							@RequestParam(defaultValue = "", required = true, value = "urlName") String urlName,
							@RequestParam(defaultValue = "", required = true, value = "url") String url,
							@RequestParam(defaultValue = "", required = true, value = "status") String status,
							@RequestParam(defaultValue = "", required = true, value = "delFlag") String delFlag,
							@RequestParam(defaultValue = "", required = true, value = "id") String id){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				pluginApiService.modifyUrl(urlName, url, status, delFlag, id);
				return resultJson(PluginResultObj.CODE_SUCCESS,"操作成功",null);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	/**
	 * 奖惩列表
	 * @param token token秘钥
	 * @param ztmc 主体名称
	 * @param jclb 奖惩类别 C:惩戒 J:激励
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @param page 分页条件
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/jcList")
	public Object jcList(@RequestParam(defaultValue = "", required = true, value = "token") String token,
						 @RequestParam(defaultValue = "", required = true, value = "ztmc") String ztmc,
						 @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb,
						 @RequestParam(defaultValue = "", required = true, value = "startTime") String startTime,
						 @RequestParam(defaultValue = "", required = true, value = "endTime") String endTime,
						 Page page){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				String deptId= officeService.selectTopDeptId((String) userInfo.get("deptId"));

				Map<String,Object> content=new HashMap<>();
				content.put("data",pluginApiService.selectJcListForPage(deptId,ztmc, jclb, page,startTime,endTime));
				content.put("totalCount",page.getTotalCount());

				return resultJson(PluginResultObj.CODE_SUCCESS,"查询成功",content);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	@ResponseBody
	@RequestMapping(value = "/jcDetail")
	public Object jcDetail(@RequestParam(defaultValue = "", required = true, value = "token") String token,
						   @RequestParam(defaultValue = "", required = true, value = "ztmc") String ztmc,
						   @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				String deptId= officeService.selectTopDeptId((String) userInfo.get("deptId"));

				return resultJson(PluginResultObj.CODE_SUCCESS,"查询成功",pluginApiService.selectJcDetail(ztmc, jclb,pluginApiService.getLabel(deptId,ztmc, jclb)));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	/**
	 * 反馈列表
	 * @param token token秘钥
	 * @param ztmc 主体名称
	 * @param jclb 奖惩类别 C:惩戒 J:激励
	 * @param status 反馈状态 Y:已反馈 N:未反馈
	 * @param startTime 开始时间
	 * @param endTime 结束时间
	 * @param page 分页条件
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/feedbackList")
	public Object feedbackList(@RequestParam(defaultValue = "", required = true, value = "token") String token,
							   @RequestParam(defaultValue = "", required = true, value = "ztmc") String ztmc,
							   @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb,
							   @RequestParam(defaultValue = "", required = true, value = "status") String status,
							   @RequestParam(defaultValue = "", required = true, value = "startTime") String startTime,
							   @RequestParam(defaultValue = "", required = true, value = "endTime") String endTime,
							   Page page){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				String deptId= officeService.selectTopDeptId((String) userInfo.get("deptId"));

				Map<String,Object> content=new HashMap<>();
				content.put("data",pluginApiService.selectFeedbackListForPage(deptId,ztmc,page,jclb,status,startTime,endTime));
				content.put("totalCount",page.getTotalCount());

				return resultJson(PluginResultObj.CODE_SUCCESS,"查询成功",content);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	@ResponseBody
	@RequestMapping(value = "/feedbackDetail")
	public Object feedbackDetail(@RequestParam(defaultValue = "", required = true, value = "token") String token,
								 @RequestParam(defaultValue = "", required = true, value = "ztmc") String ztmc,
								 @RequestParam(defaultValue = "", required = true, value = "jclb") String jclb){
		// 非空
		if(!StringUtils.isEmpty(token)){
			//Base64解析token获取用户id
			try {
				long userId=Long.parseLong(new String(Base64.getDecoder().decode(token),"utf-8"));
				LinkedHashMap userInfo=pluginApiService.getUserInfo(userId+"").getData();

				if(null==userInfo || userInfo.get("deptId")==null){
					return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
				}

				String deptId= officeService.selectTopDeptId((String) userInfo.get("deptId"));

				Map<String,Object> content=new HashMap<String, Object>();
				LinkedHashMap companyInfo=pluginApiService.getCompanyInfo(ztmc).getData();
				String label = pluginApiService.getLabel(deptId,ztmc, jclb);
				companyInfo.put("label",label);
				content.put("companyInfo",companyInfo);
				content.put("feedbackInfo",pluginApiService.selectFeedbackDetail(ztmc, jclb,pluginApiService.getLabel(deptId,ztmc,jclb)));

				return resultJson(PluginResultObj.CODE_SUCCESS,"查询成功",content);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
			}
		}

		return resultJson(PluginResultObj.CODE_FAIL,"请重新登录",null);
	}

	/**
	 * 接口返回值
	 * @param code
	 * @param mess
	 * @param content
	 * @return
	 */
	private Object resultJson(String code,String mess,Object content){
		return new PluginResultObj(code,mess,content);
	}
}
